import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from flask import Flask, request, jsonify, send_file
from utils import zip_folder
from translator import PDFTranslator

app = Flask(__name__)

@app.route('/translate_pdf', methods=['POST'])
def translate_pdf(debug=False):
    # 从 POST 请求中获取翻译所需的参数
    data = request.json
    model_type = data.get('model_type')
    model = data.get('model')
    target_language = data.get('target_language')
    filepath = data.get('filepath')

    if debug:
        print(f'model_type: {model_type}')
        print(f'model: {model}')
        print(f'target_language: {target_language}')
        print(f'filepath: {filepath}')

    # 使用工厂模式创建翻译模型实例
    output_file_path = os.path.splitext(filepath)[0]
    translator = PDFTranslator(model_type, model)

    # 执行 PDF 翻译
    translator.translate_pdf(filepath, 'markdown', output_file_path, target_language)

    # 创建压缩文件
    zip_file_path = zip_folder(output_file_path, os.path.dirname(filepath))

    # 返回翻译后的压缩文件
    if zip_file_path:
        return send_file(zip_file_path, as_attachment=True)
    else:
        return jsonify({'error': 'Translate Failed.'})


if __name__ == '__main__':
    app.run(port=8080, debug=True)
    '''
curl -X POST -H "Content-Type: application/json" -d '{
    "model_type": "OpenAI",
    "model": "gpt-3.5-turbo",
    "target_language": "Chinese",
    "filepath": "input_files/book1.pdf"
}' http://127.0.0.1:8080/translate_pdf
    '''